# c: & cd "C:\Program Files\PythonForS60"
# ensymble.py py2sis i:camera_tests.py i:

import appuifw, e32
import os
import sys
import time
import traceback

# Must set landscape mode *before* importing camera2 module!
appuifw.app.screen = "large" # 'full' == no menu to exit!
appuifw.app.orientation = "landscape"
#appuifw.app.directional_pad = False

#import camera2
import camera2 as camera

MY_DEBUG = True
LOCAL_FOLDER = "E:\\"

def GetCurrentTime():
    if (e32.s60_version_info[0] < 3):
        #PyS60 1.4.5 running on S60 2nd edition has the issue with displaying the current hour + 2 (mod 24)
        return time.localtime(time.time() - 2 * 3600)

    return time.localtime()


stdoutFile = None
stderrFile = None
stdoutFileName = None
stderrFileName = None
def CreateDirectoriesAndLogFiles():
     global stdoutFile, stderrFile
     global stdoutFileName, stderrFileName
     global LOCAL_FOLDER, LOCAL_FOLDER_MEDIA_FILES, LOCAL_FOLDER_MEDIA_FILES_UNSENT
     global STATE_FILENAME

     #LOCAL_FOLDER_MEDIA_FILES = LOCAL_FOLDER + "\\Media"
     #LOCAL_FOLDER_MEDIA_FILES_UNSENT = LOCAL_FOLDER + "\\Unsent"
     #STATE_FILENAME = LOCAL_FOLDER + "\\state.bin"

     try:
         if not os.path.exists(LOCAL_FOLDER):
             os.makedirs(LOCAL_FOLDER)
         """
         if not os.path.exists(LOCAL_FOLDER_MEDIA_FILES):
             os.makedirs(LOCAL_FOLDER_MEDIA_FILES)
         if not os.path.exists(LOCAL_FOLDER_MEDIA_FILES_UNSENT):
             os.makedirs(LOCAL_FOLDER_MEDIA_FILES_UNSENT)
         """

         if (MY_DEBUG):
             sys.stdout.flush()
             sys.stderr.flush()

             STDDateTime = time.strftime("_%Y_%m_%d_%H_%M_%S", GetCurrentTime())

             stderrFileName = LOCAL_FOLDER + "\\camera2_stderr" + STDDateTime + ".txt"
             stderrFile = open(stderrFileName, "a")
             sys.stderr = stderrFile

             stdoutFileName = LOCAL_FOLDER + "\\camera2_stdout" + STDDateTime + ".txt"
             stdoutFile = open(stdoutFileName, "a")
             sys.stdout = stdoutFile

             sys.stdout.flush()
             sys.stderr.flush()
     except:
         if (MY_DEBUG):
             traceback.print_exc()
             sys.stdout.flush()
             sys.stderr.flush()

CreateDirectoriesAndLogFiles()


app_lock = e32.Ao_lock()
def quit():
    camera.stop_finder() # Close the viewfinder
    camera.release()     # Release the camera2 so that other programs can use it
    app_lock.signal()
appuifw.app.exit_key_handler = quit

def log(msg):
    print msg
    logPathFileName = u"E:\\camera2_tests.log"
    f = open(logPathFileName, "a")
    f.write("%s\n" % msg)
    f.close()

printed = False

# ViewFinder function; basically it just displays an image on a Canvas
def vf(im):
    global printed
    if not printed:
        log("VF size: %s" % [im.size])
        printed = True
    if (e32.s60_version_info[0] == 5 and e32.s60_version_info[0] == 2):
        appuifw.app.body.begin_redraw()
        appuifw.app.body.blit(im)
        appuifw.app.body.end_redraw()
    else:
        appuifw.app.body.blit(im)


appuifw.app.body = appuifw.Canvas() # Set the application's body to Canvas

def video_callback(err, current_state):
    global control_light   
    if current_state == camera.EPrepareComplete:
        log("camera2.EPrepareComplete")
    if err:
        msg = "video_callback error: %s", err
        log(msg)

savepath = u"E:\\camera2_video.mp4"

video = 0

def SetMenu(state):
    if state == 0:
        appuifw.app.menu = [(u"Record video",   start_rec)]
    else: 
        appuifw.app.menu = [(u"Stop recording", stop_rec)]

def stop_rec():
    SetMenu(0);
    log("Stopping recording")
    camera.stop_record()

def start_rec():
    SetMenu(1);
    log("Starting recording")
    global video
    #video = camera.start_record(savepath, video_callback, frameSize = (1280, 720), fps = 25.0, bitrate = 5000000, videotype = 'H264AVCBPL31') #frameSize=(640,480))
    #video = camera.start_record(savepath, video_callback, frameSize = (320, 240), fps = 15.0)
    #video = camera.start_record(savepath, video_callback, frameSize = (640, 480), fps = 30.0)

    #video = camera.start_record(savepath, video_callback, frameSize = (320, 240), frameRate = 5.0) #records at 15 fps (closest value to 5.0)

    #video = camera.start_record(savepath, video_callback, frameSize = (320, 240), format = "YUV420p", frameRate = 15.0, videoType = "video/mp4v-es; profile-level-id=4", audioEnabled = False)
    video = camera.start_record(savepath, video_callback, format = "YUV420p", frameSize = (320, 240), frameRate = 15.0, videoType = "video/mp4v-es; profile-level-id=4", audioEnabled = False)

    #video = camera.start_record(savepath, video_callback, frameSize = (640, 480)) #, fps = 15.0)
    
    #video = camera.start_record(savepath, video_callback, frameSize = (176, 144)) #, fps = 15.0)

SetMenu(0)


camera.release()
#camera._my_camera = camera._camera.Camera(1)
camera._my_camera = camera._camera.Camera(0)

# debug info
log("--")

log("Cameras avail.: %s" % camera.cameras_available())   # 2
log("Image modes   : %s" % camera.image_modes())         # RGB12, RGB, JPEG_Exif, RGB16
log("Image sizes   : %s" % camera.image_sizes())         # 1024x768, 640x480
log("Flash modes   : %s" % camera.flash_modes())         # auto, none, red_eye_reduce, forced
log("Max zoom      : %s" % camera.max_zoom())            # 70
log("Exposure modes: %s" % camera.exposure_modes())      # auto, center, backlight, night
log("White balance : %s" % camera.white_balance_modes()) # auto, cloudy, daylight, tungsten, fluorescent

camera.image_sizes("JPEG_Exif")
log("Modemaps      : %s" % camera.modemap)
for m in camera.modemap.values():
    for i in range(camera._my_camera.max_image_size()):
        s = camera._my_camera.image_size(m, i)
        if (s != (0, 0)):
            log("Mode %3d, size %2d: %4d x %4d, Prop: %4.2f" % (m, i, s[0], s[1], float(s[0]) / float(s[1])) )

log("Video formats       : %s" % camera.video_formats())        # New!
log("Frame sizes         : %s" % camera.frame_sizes())          # New!
log("Video configurations: %s" % camera.frame_rates())          # New!

for mode in camera.video_formats():
    for i in range(camera._my_camera.GetNumVideoFrameSizesSupported()):
       s=camera._my_camera.frame_size(camera.formatmap[mode], i)
       if s!=(0,0):
           log("Mode %-8.8s, index %d, res. %4d x %4d" % (mode, i, s[0], s[1]))
           #~ for f in range(camera._my_camera.GetNumVideoFrameRatesSupported()):
           #~   r=camera._my_camera.frame_rate(camera.formatmap[mode], f, i, camera.exposuremap['auto'])
           #~   log("    rate: index %d, value %5.2f" % (f, r))


#camera.start_finder(vf, backlight_on = 0, size=(320, 240))
camera.start_finder(vf, backlight_on = 0, size = (176, 144))

#camera.start_finder(vf, backlight_on = 0, size=(480, 360))
#camera.start_finder(vf, backlight_on = 1, size=(240, 180))

app_lock.wait()

log("Normal exit")